﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using SeeSharpTools.JY.Socket.ValueHelper;

namespace SimpleTCPClient
{
    public partial class ClientForm : Form
    {
        private TcpClient client = null;
        bool check = true;

        public ClientForm()
        {
            InitializeComponent();
        }

        private void btn_Link_Client_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                if (client.Connected == true)
                    return;
            }
            IPAddress myIPClient = IPAddress.Parse(this.textIP_Client.Text);
            IPEndPoint MyServer = new IPEndPoint(myIPClient, Int32.Parse(this.textPort_Client.Text));
            client = new TcpClient();
            try
            {
                client.Connect(MyServer);
                this.textState_Client.Text = "Connect Success!";
                Thread thread = new Thread(new ThreadStart(accpClient));
                check = true;
                thread.IsBackground = true;
                thread.Start();
            }
            catch (Exception ex)
            {
                this.textState_Client.Text = "Error:" + ex.Message;
                client = null;
            }
            btn_Link_Client.Enabled = false;
        }

        private void accpClient()
        {
            Control.CheckForIllegalCrossThreadCalls = false;//消線程保護
            //Thread.Sleep(5000);
            try
            {
                while (check)
                {
                    NetworkStream netStream = client.GetStream();
                    Byte[] Rec = new Byte[4];

                    netStream.Read(Rec, 0, Rec.Length);

                    Byte[] WaveData = new Byte[BigEndianValueHelper.GetInt(Rec)];
                    netStream.Read(WaveData, 0, WaveData.Length);

                    Action act = () => easyChart1.Plot(BigEndianValueHelper.GetDoubleArray(WaveData));
                    easyChart1.Invoke(act);//这个才是同步的


                }
            }
            catch (Exception)
            {
                client.Close();
                this.textState_Client.Text = "Connect Cancel!";
                btn_Link_Client.Enabled = true;
            }
        }

        private void btn_Send_Client_Click(object sender, EventArgs e)
        {
            client?.Close();

            check = false;
            btn_Link_Client.Enabled = true;

            this.textState_Client.Text = "Connect Cancel!";
        }
    }
}
